using System;
using System.Configuration;
using System.Reflection;
using Castle.ActiveRecord;
using ModelGenerator.RepositoryGenerator.Builders;

namespace ModelGenerator.RepositoryGenerator
{
    public class RepositoryGenerator
    {
        public static void GenerateRepositories(Type modelClass)
        {
            foreach (Type type in modelClass.Assembly.GetTypes())
            {
                if (isActiveRecordClass(type))
                    GenerateCustomRepository(type);
            }
        }

        /// <summary>
        /// Generates the custom repository.
        /// </summary>
        /// <param name="type">The type.</param>
        private static void GenerateCustomRepository(Type type)
        {
            var RepositoryBuilder = new ARRepositoryBuilder
                                        {
                                            BaseType = ConfigurationManager.AppSettings["BaseType"],
                                            DomainClassName = type.Name,
                                            SourceNameSpace = type.Namespace,
                                            BaseTypeNameSpace = ConfigurationManager.AppSettings["BaseTypeNameSpace"],
                                            TargetNameSpace = ConfigurationManager.AppSettings["RepositoryNamespace"],
                                            MemberType = type.GetProperties()
                                        };

            RepositoryBuilder.CreateARRepository();
            RepositoryBuilder.CreateFiles(ConfigurationManager.AppSettings["TargetRepositoryDirectory"]);
        }

        /// <summary>
        /// Determines whether [is active record class] [the specified type].
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if [is active record class] [the specified type]; otherwise, <c>false</c>.
        /// </returns>
        private static bool isActiveRecordClass(ICustomAttributeProvider type)
        {
            object[] attributes = type.GetCustomAttributes(typeof (ActiveRecordAttribute), true);
            return (attributes.Length > 0);
        }
    }
}